package com.itic.ht.cms.studyrecord.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.ht.cms.questype.persistence.model.QuestionType;
import com.itic.ht.cms.questype.service.QuestionTypeService;
import com.itic.ht.cms.studyrecord.persistence.model.StudyRecord;
import com.itic.ht.cms.studyrecord.persistence.model.StudyRecordExample;
import com.itic.ht.cms.studyrecord.persistence.model.StudyRecordExample.Criteria;
import com.itic.ht.cms.studyrecord.service.StudyRecordService;
import com.itic.ht.mem.mtype.service.WebmTypeService;

@Controller
@RequestMapping(value = "/cms/studyrecord")
public class StudyRecordController extends BaseController {

	@Autowired
	protected StudyRecordService studyRecordService;
    @Autowired
   	protected OutCommonService outCommonService;
    @Autowired
    private WebmTypeService webmTypeService;
    @Autowired
    private QuestionTypeService questionTypeService;
    
	////////////////////////////////////////////////////// 常量区////////////////////////////////////////////////////////////////
	private static final String MODEL_NAME_CHINA = "学习记录";// 中文名
	private static final String MODEL_NAME＿ENGLISH = "questype";// 英文名
	private static final String PAGE_COMMON_PATH = "/cms/studyrecord/studyrecord";// 通用路径
	private static final String COMMON_URL = "/cms/studyrecord/";// 通用路径

	// 返回属性黑名单
	private static String[] ignoreProperties = new String[] { "mtime" };

	////////////////////////////////////////////////////// 页面跳转区////////////////////////////////////////////////////////////

	/*
	 * 主页面
	 */
	@RequestMapping(value = "/init")
	public String init(Model model) {
		model.addAttribute("name_china", MODEL_NAME_CHINA);
		model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
		model.addAttribute("common_url", COMMON_URL);
		return PAGE_COMMON_PATH + "Main";
	}
	/*
     * 添加页面
     */
    @RequestMapping(value="/initAdd")
    public String initAdd(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Add";
    }
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/add")
    @ResponseBody
    public Map<String,String> add(StudyRecord templet){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = studyRecordService.add(templet);
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /*
     * 编辑页面
     */
    @RequestMapping(value="/initEdit")
    public String initEdit(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		StudyRecord temp = studyRecordService.get(id);
    		model.addAttribute("editData",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	return PAGE_COMMON_PATH+"Edit";
    }
    
    /**
     * 编辑保存
     * @param templet
     * @return
     */
    @RequestMapping(value="/edit")
    @ResponseBody
    public Map<String,String> edit(StudyRecord templet){
    
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = studyRecordService.edit(templet);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, String> del(String ids) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //批量删除
        if (StringHelper.isNotBlank(ids)) {
            List<String> idList = Arrays.asList(ids.split(","));
            StudyRecordExample example = new StudyRecordExample();
            example.createCriteria().andIdIn(idList);
          
            StudyRecord templet = new StudyRecord();
            result = studyRecordService.deleteByExample(templet, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        //删除一个
        /*
        if( StringHelper.isNotBlank(id) ){
            Templet templet = new Templet();
            templet.setId(id);
            result = templetService.delete(templet);
        }
        */
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(StudyRecord templet, HttpServletRequest request) {
		// 声明返回对象
		Map<String, Object> resultMap = new HashMap<String, Object>();

		StudyRecordExample example = this.queryCondition(request, templet);
		// 封装分页参数
		example = this.handlePageQuery(request, example);

		// 获取信息总条数
		int total = studyRecordService.count(example);

		// 获取数据
		List<StudyRecord> list = studyRecordService.list(example);

		// 结果集
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (list.size() > 0) {
			for (StudyRecord temp : list) {
				temp.setCategory(webmTypeService.get(temp.getCategory()).getName());
				temp.setStudyContent(questionTypeService.getTypeName(temp.getStudyContent()).getName());
			}
			// 过滤黑名单字段
			resultList = ValueHelper.tranList2MapList(list, ignoreProperties);
		}

		// 数据返回处理
		resultMap.put(IticConst.TOTAL_RECORDS, total);
		resultMap.put(IticConst.DISPLAY_RECORDS, total);
		resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
		resultMap.put(IticConst.DATA, resultList);
		return resultMap;

	}

	/**
	 * 获取request中的指定参数，并进行trim处理.
	 * 
	 * @param request @param paramName @return @throws
	 */
	protected String getCleanParams(HttpServletRequest request, String paramName) {
		String result = null;
		String param = request.getParameter(paramName);
		result = StringHelper.getCleanString(param);
		return result;
	}

	/**
	 * <p>
	 * Title:queryCondition
	 * </p>
	 * <p>
	 * Description:封装查询条件
	 * </p>
	 * 
	 * @param request
	 * @param templet
	 * @return
	 */
	private StudyRecordExample queryCondition(HttpServletRequest request, StudyRecord templet) {
		// 参数处理
		StudyRecordExample example = new StudyRecordExample();
		// 按照创建时间倒叙
		example.setOrderByClause("ctime desc");
		// 查询条件
		Criteria criteria = example.createCriteria().andDelFlagEqualTo(1);
		if (null != templet) {
			// 姓名查询
			if (StringHelper.isNotBlank(templet.getRealname())) {
				criteria.andRealnameLike("%" + templet.getRealname() + "%");
			}
			// 会员级别查询
			if (StringHelper.isNotBlank(templet.getCategory())) {
				criteria.andCategoryEqualTo(templet.getCategory());
			}
		}
		return example;
	}

}
